//图片懒加载模块

import eventBus from "@/eventBus.js";//导入事件总线
import { debounce } from "@/utils";//导入防抖函数
import defaultSrc from "@/assets/default.gif";//默认图片地址

var images = [];//定义数组，存储需要处理的图片

eventBus.$on('mainScroll', debounce(setImages, 50));//监听主区域滚动，滚动则触发setImages函数


function setImg(img) {
    img.dom.src = defaultSrc;//暂时设定为默认图片

    const rect = img.dom.getBoundingClientRect();
    const clientHeight = document.documentElement.clientHeight;//可视区高度
    const height = rect.height || 150;//图片元素的高度
    if (rect.top >= -height && rect.top <=clientHeight) {
        //图片在可视区范围内
        img.dom.src = img.src;

        images = images.filter(i => {
            return i !== img
        })
    }

}


//处理待处理的图片数组
function setImages() {
    for (let img of images) {
        setImg(img);
    }
}





export default {
    //当绑定元素插入到DOM中时
    inserted: function (el, binding) {
        const img = {
            dom: el,
            src: binding.value
        }
        images.push(img);
        setImg(img);
    },

    //指令与元素解绑时
    unbind(el, binding) {
        images = images.filter(img => {
            return img.dom == el;
        })
    }
}

